<script>
import WrapTable from '@/components/WrapTable'
import ButtonList from '@/components/ButtonList'
import TableButtonList from '@/components/TableButtonList'
import DialogForm from '@/components/DialogForm'
import { commonMixin } from '@/mixins/common'
import ComponentsSelect from '../privateComponents/componentsSelect.vue'
import componentsSelectEvent from '../event/componentsSelectEvents.js'
import handle from '../event/handle.js'
import request from '@/utils/request.js'
import store from '../store'
import { getCodeList } from '@/api/dictionary'

const srcObj = {
  cType: '',
  cascaderValue: [],
  componentName: '',
  radioVal: '', // 值有'',1，2，3 ''表示业务对象为非机构，1代表本机构 2代表本机构及下级机构 3代表其他机构及下级机构
  operatorsVal: '',
  conditionsVal: '',
  conditions2Val: '',
  conditionsDirectoryVal: [], // 必须添加，否则watch不到数据变化，条件下拉选择始终无数据
  datesVal: '',
  checkedTreeNodes: [],
  checkedTreeNodeNames: '',
  codeOperatorsVal: '',
  groupTreeCheckedNodes: [], // 存储每个条件中如果有选择机构树情况下机构树节点勾选
  refName: 'ComponentsSelect',
  bustypeDesc: '',
  bustypeDescbak: ''
}

export default {
  name: 'conditionConfig',
  mixins: [commonMixin, componentsSelectEvent, handle, store],
  inject: ['Dialog'],
  components: {
    WrapTable,
    ButtonList,
    ComponentsSelect
  },
  props: {
    datagroupId: {
      required: true,
      type: String,
      default: ''
    }
  },
  data() {
    return {
      data: [],
      allResultsymbolData: [],
      allCodeTypeListData: [],
      allBusinessobjectData: [],
      conditionObj: Object.assign({}, srcObj),
      tableSelectionCol: false,
      tableIndexCol: false,
      pagination: false,
      btnListWidthPercent: 18,
      btnListWidthOffset: 0,
      objId: '',
      tableOptWidth: '80',
      innerDialogType: '',
      toolPanelBtnList: this.addBtns,
      reloadSmallTreeFlag: true,
      showSmallTree: false,
      index: '',
      findDimensionBustypeUrl: '/v1/yq/datagroup/findDimensionBustypeById', // 获取条件url
      getCodeTypeListUrl: '/v1/dataProvider/getCodeTypeList', // 获取代码url
      resultsymbolUrl: '/v1/yq/resultsymbol/cykablyat', // 获取运算符url
      businessobjectUrl: '/v1/yq/meatbustype/query',
      getGroupNameByIdsUrl: '/v1/yq/datagroup/getGroupNameByIds',
      deleteUrl: '/v1/yq/datagroup/deleteBusType',
      saveConditionUrl: '/v1/yq/datagroup/addCondition',
      cascaderOptions: [
        { label: '业务对象', value: '1', children: [] },
        { label: '代码', value: '2', children: [] }
      ],
      columns: [
        {
          prop: 'specialType',
          label: '条件分类',
          sortable: true,
          'header-align': 'center',
          width: '105',
          'show-overflow-tooltip': true,
          align: 'left',
          formatter: (row, column, cellValue) =>
            cellValue === 0
              ? row.dicCodeType
                ? '代码类型'
                : '业务对象'
              : '机构'
        },
        {
          prop: 'bustypeObjId',
          label: '业务对象/代码类型/授权方式',
          sortable: true,
          'header-align': 'center',
          'show-overflow-tooltip': true,
          width: '230',
          align: 'left',
          formatter: (row, column, cellValue) => {
            if (row.specialType) {
              return '机构'
            } else if (!row.dicCodeType) {
              if (this.allBusinessobjectData) {
                return this.allBusinessobjectData.filter(
                  item => item.objId === cellValue
                )[0].objName
              } else {
                return ''
              }
            } else {
              if (this.allCodeTypeListData) {
                return this.allCodeTypeListData.filter(
                  item => item.type === row.dicCodeType
                )[0].name
              } else {
                return ''
              }
            }
          }
        },
        {
          prop: 'bustypeCondition',
          label: '运算符',
          sortable: true,
          'header-align': 'center',
          width: '120',
          'show-overflow-tooltip': true,
          align: 'left',
          formatter: (row, column, cellValue) => {
            if (row.specialType) {
              return ''
            } else {
              if (cellValue) {
                return this.allResultsymbolData.filter(
                  item => item.objId === cellValue
                )[0].symbolName
              }
              return ''
            }
          }
        },
        {
          prop: 'bustypeDesc',
          label: '条件',
          ref: 'bustypeDesc',
          sortable: true,
          'header-align': 'center',
          width: '120',
          'show-overflow-tooltip': true,
          align: 'left',
          scopedSlots: {
            default: scope => {
              if (scope.row.specialType) {
                return ''
              } else if (!scope.row.dicCodeType) {
                return <div>{scope.row.bustypeDesc}</div>
              } else {
                if (scope.row.codeList.length > 0) {
                  return scope.row.codeList.filter(
                    item => item.codeId == scope.row.bustypeDesc
                  )[0].codeName
                }
                return ''
              }
            }
          }
        },
        // { prop: 'bustypeDesc', label: '分配机构', sortable: true, 'min-width': '120', 'header-align': 'center', 'show-overflow-tooltip': true, align: 'center',
        {
          prop: 'groupName',
          label: '分配机构',
          sortable: true,
          'min-width': '120',
          'header-align': 'center',
          'show-overflow-tooltip': true,
          align: 'center',
          formatter: (row, column, cellValue) => {
            if (row.specialType) {
              if (parseInt(row.specialType) === 1) {
                return '本机构'
              } else if (parseInt(row.specialType) === 2) {
                return '本机构及下级机构'
              } else {
                return cellValue
              }
            } else {
              return ''
            }
          }
        }
      ]
    }
  },
  watch: {
    'Dialog.visible': {
      immediate: true,
      handler(val) {
        val && this.init()
      }
    }
  },
  methods: {
    // 初始化
    init() {
      const promise = []
      promise.push(this.getAllBusinessData())
      promise.push(this.getAllResultsymbolData())
      promise.push(this.getAllCodeTypeListDataInfo())
      promise.push(this.getConditionData({ datagroupId: this.datagroupId }))
      Promise.all(promise)
        .then(results => {
          this.allBusinessobjectData = results[0]
          this.allResultsymbolData = results[1]
          this.allCodeTypeListData = results[2]
          this.data = results[3]
        })
        .catch(err => {
          console.log(err)
        })
    },
    getAllCodeTypeListDataInfo() {
      return new Promise((resolve, reject) => {
        this.getCodeTypeListInfo().then(({ success, data }) => {
          if (success) {
            this.cascaderOptions[1].children = data.map(item => {
              // 获取代码的数据，并根据需要修改其形式
              return {
                value: item.type,
                label: item.name
              }
            })
            resolve(data)
          } else {
            reject(new Error('获取代码类型信息失败！'))
          }
        })
      }).catch(err => {
        console.log(err)
        reject(err)
      })
    },
    getAllBusinessData() {
      return new Promise((resolve, reject) => {
        this.getBusinessobjectData().then(({ success, data }) => {
          if (success) {
            data.forEach(item => {
              const obj = {}
              obj.label = item.objName
              obj.value = item.objId
              obj.formatType = item.formatType
              this.cascaderOptions[0].children = []
              this.$nextTick(() => {
                this.cascaderOptions[0].children.push(obj) // 获取业务对象的数据，并根据需要修改其形式
              })
            })
            resolve(data)
          } else {
            this.$message({
              type: 'error',
              message: '获取业务对象数据失败'
            })
            reject(new Error('获取业务对象数据失败'))
          }
        })
      }).catch(err => {
        console.log(err)
        reject(err)
      })
    },
    getAllResultsymbolData() {
      return new Promise((resolve, reject) => {
        this.getResultsymbolData().then(({ success, data }) => {
          if (success) {
            resolve(data)
          } else {
            reject(new Error('获取运算符数据失败！'))
          }
        })
      }).catch(err => {
        console.log(err)
        reject(err)
      })
    },
    handleEditSubmit() {
      return this.$refs.editForm
        .validate()
        .then(() => {
          return this.update(this.formPanel.edit.model)
        })
        .then(({ success, message }) => {
          this.$message({
            type: success ? 'success' : 'error',
            message: message
          })
          if (success) {
            this.$refs.table.load()
            this.dialogType = ''
          } else {
            throw new Error(message)
          }
        })
        .catch(err => {
          console.log(err)
          return Promise.reject(err)
        })
    },
    getConditionData(params) {
      return new Promise(resolve => {
        request({
          url: this.findDimensionBustypeUrl,
          method: 'get',
          params
        }).then(({ success, data }) => {
          if (success) {
            resolve(data)
          } else {
            this.$message({
              type: 'error',
              message: '获取数据组详情失败！'
            })
          }
        })
      })
    },
    handleAdd() {
      // this.dateIsShow = false
      // this.inputIsShow = false
      this.innerDialogType = 'add'
      this.conditionObj = Object.assign({}, srcObj)
    },
    handleEdit(row) {
      this.handleEditConditionObj(row)
      this.innerDialogType = 'edit'
    },
    handleEditConditionObj(row) {
      this.objId = row.objId
      this.conditionObj = {
        cType: '',
        cascaderValue: [],
        componentName: '',
        radioVal: '',
        operatorsVal: '',
        conditionsVal: '',
        conditions2Val: '',
        conditionsDirectoryVal: [], // 必须添加，否则watch不到数据变化，条件下拉选择始终无数据
        datesVal: '',
        checkedTreeNodes: [],
        checkedTreeNodeNames: '',
        codeOperatorsVal: '',
        groupTreeCheckedNodes: [], // 存储每个条件中如果有选择机构树情况下机构树节点勾选
        refName: 'ComponentsSelect',
        bustypeDesc: '',
        bustypeDescbak: ''
      }
      /**
       *  非业务对象
       */
      if (!row.bustypeObjId) {
        /**
         * 代码
         */
        this.conditionObj.cType = 'codeType'
        this.conditionObj.componentName = 'Codes'
        this.conditionObj.cascaderValue = ['2', row.dicCodeType] // 业务对象
        this.conditionObj.codeOperatorsVal = row.bustypeCondition // 运算符
        this.conditionObj.conditionsVal = +row.bustypeDesc // 条件
        getCodeList(row.dicCodeType).then(({ data }) => {
          data.length > 0 && (this.conditionObj.conditionsDirectoryVal = data)
        })
      } else if (row.specialType !== 0) {
        /**
         * 特殊业务对象
         */

        this.conditionObj.cType = 'specialType'
        this.conditionObj.componentName = 'SpecialObj'
        this.conditionObj.radioVal = row.specialType + '' // 单选框
        this.conditionObj.bustypeDesc = row.bustypeDesc
        this.conditionObj.bustypeDescbak = row.bustypeDescbak
        if (row.bustypeDesc) {
          this.showSmallTree = true
        }
        this.reloadTreeFlag = true
        this.conditionObj.objId = row.objId
        this.conditionObj.cascaderValue = ['1', row.bustypeObjId] // 业务对象
      } else {
        /**
         * 普通业务对象
         */
        this.conditionObj.cType = 'commonType'
        this.conditionObj.componentName = 'CommonObj'
        this.conditionObj.cascaderValue = ['1', row.bustypeObjId] // 业务对象
        this.conditionObj.operatorsVal = row.bustypeCondition // 运算符

        if (row.formatType == 'TM') {
          this.dateIsShow = true
          this.conditionObj.datesVal = row.bustypeDesc // 条件
        } else {
          this.inputIsShow = true
          this.conditionObj.conditions2Val = row.bustypeDesc // 条件
        }
      }
    },
    handleDelete(row) {
      return this.$confirm(
        '此操作不能回退，确认要删除您选中的数据么?',
        '提示',
        {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }
      )
        .then(() => {
          return request({
            url: this.deleteUrl,
            method: 'get',
            params: {
              objId: row.objId,
              datagroupId: this.datagroupId
            }
          })
        })
        .then(({ success, message }) => {
          this.$message({
            customClass: 'datagroup-message',
            type: success ? 'success' : 'error',
            message
          })
          if (success) {
            this.getConditionData({ datagroupId: this.datagroupId }).then(
              result => {
                this.data = result
              }
            )
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            customClass: 'datagroup-message',
            type: error === 'cancel' ? 'info' : 'error',
            message:
              error === 'cancel'
                ? '已取消删除'
                : error instanceof Error
                ? error.message
                : error
          })
        })
    },
    handleCancel() {
      this.innerDialogType = ''
    },
    // 保存条件
    handleSubmit() {
      const obj = {
        dicCodeType: '',
        bustypeObjId: '', // 业务id
        bustypeCondition: '', // 操作符 id
        bustypeDesc: '', // 条件
        bustypeDescbak: '',
        specialType: '0' // 单选框
      }
      if (this.innerDialogType !== 'add' && this.innerDialogType !== '') {
        obj.objId = this.objId
      }
      // 业务对象选择机构
      if (this.conditionObj.radioVal) {
        obj.specialType = this.conditionObj.radioVal
        obj.bustypeObjId = '88bc27b5-a9c2-11e8-aaa0-00ff592a9fc2' // 机构业务id
        // 其他机构及下级机构
        if (this.conditionObj.radioVal === '3') {
          const idArr = []
          const pidArr = []
          this.conditionObj.groupTreeCheckedNodes.forEach(v => {
            idArr.push(v.id)
            pidArr.push(v.parentNode ? v.parentNode : '')
          })
          // 避免编辑打开后未改变所选机构而造成保存报错
          if (this.conditionObj.groupTreeCheckedNodes.length) {
            // 筛选出被全勾选的且非叶子节点的id值
            const filterIds = idArr.filter(item =>
              [...new Set(pidArr)].includes(item)
            )
            // 剔除那些节点的parentNode（即父亲节点id值）在filterIds里的节点
            const filterNodes = this.conditionObj.groupTreeCheckedNodes.filter(
              item => !filterIds.includes(item.parentNode)
            )
            obj.bustypeDescbak = filterNodes
              .map(item => {
                return item.groupNo
              })
              .join(',')
            const arr = []
            this.conditionObj.checkedTreeNodes.forEach(_item => {
              arr.push(_item.id)
            })
            obj.bustypeDesc = String(arr) // 树-传给后台的数据只要是id即可
          } else {
            obj.bustypeDesc = this.conditionObj.bustypeDesc
            obj.bustypeDescbak = this.conditionObj.bustypeDescbak
          }
        }
      } else if (this.conditionObj.cascaderValue[0] === '1') {
        // 普通业务对象
        obj.bustypeObjId = this.conditionObj.cascaderValue[1]
        obj.bustypeCondition = this.conditionObj.operatorsVal
        obj.bustypeDesc = this.conditionObj.conditions2Val
          ? this.conditionObj.conditions2Val
          : this.conditionObj.datesVal
      } else {
        // 代码
        obj.dicCodeType = this.conditionObj.cascaderValue[1]
        obj.bustypeCondition = this.conditionObj.codeOperatorsVal
        obj.bustypeDesc = this.conditionObj.conditionsVal
      }
      obj.datagroupId = this.datagroupId
      if (this.conditionObj.cascaderValue.length === 0) {
        this.$message({
          type: 'error',
          message: '业务类型不能为空！'
        })
      } else if (
        this.conditionObj.cascaderValue[1] ===
        '88bc27b5-a9c2-11e8-aaa0-00ff592a9fc2'
      ) {
        // 业务对象选择机构
        if (obj.specialType === '1' || obj.specialType === '2') {
          this.save(obj)
        } else if (
          obj.specialType === '' ||
          (obj.bustypeDesc === '' && obj.bustypeDescbak === '')
        ) {
          this.$message({
            type: 'error',
            message: '请选择具体机构！'
          })
        } else {
          this.save(obj)
        }
      } else if (
        obj.specialType === '0' &&
        obj.bustypeDesc &&
        obj.bustypeCondition
      ) {
        this.save(obj)
      } else {
        this.$message({
          type: 'error',
          message: '运算符和条件不能有空值！'
        })
      }
    },
    save(obj) {
      request({
        url: this.saveConditionUrl,
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        params: obj
      })
        .then(({ success, message }) => {
          this.$message({
            customClass: 'datagroup-message',
            type: success ? 'success' : 'error',
            message
          })
          if (success) {
            this.getConditionData({ datagroupId: this.datagroupId }).then(
              result => {
                this.data = result
              }
            )
            this.innerDialogType = ''
          }
        })
        .catch(err => console.log(err))
    },
    // eslint-disable-next-line
    renderCondition(h) {
      return (
        <div class='condition'>
          {this.renderBusinessType(h, this.conditionObj)}
          {this.renderComponentsSelect(h, this.conditionObj)}
        </div>
      )
    },
    // eslint-disable-next-line
    renderBusinessType(h, item) {
      return (
        <div class='common-box ywlx'>
          <label class='common-label'>请选择业务类型：</label>
          <div class='commonLine'>
            <c-cascader
              placeholder='请选择业务类型'
              ref='business'
              options={[this.cascaderOptions[0]]}
              {...{
                on: {
                  change: val => this.handleChange(item, val)
                }
              }}
              value={item.cascaderValue}
            />
          </div>
        </div>
      )
    },
    // eslint-disable-next-line
    renderComponentsSelect(h, item) {
      return (
        <ComponentsSelect
          ref={item.refName}
          cName={item.componentName}
          dateIsShow={this.dateIsShow}
          inputIsShow={this.inputIsShow}
          resultsymbolData={this.allResultsymbolData}
          objId={item.objId}
          value={item}
          reloadSmallTreeFlag={this.reloadSmallTreeFlag}
          showSmallTree={this.showSmallTree}
          // 特殊业务对象-单选框
          on-changeRadio={this.changeRadio.bind(this, item)}
          // 特殊业务对象-树
          on-checkTree={this.checkTree.bind(this, item)}
          on-getChecked={this.getGroupTreeChecked.bind(this, item)}
          // 代码-运算符
          on-changeCodeOperators={this.changeCodeOperators.bind(this, item)}
          // 代码-选择条件
          on-changeConditions={this.changeConditions.bind(this, item)}
          // 代码-选择条件的整个内容
          on-changeConditionsDirectory={this.changeConditionsDirectory.bind(
            this,
            item
          )}
          // 普通业务对象-运算符
          on-changeOperators={this.changeOperators.bind(this, item)}
          // 普通业务对象-输入条件（常规文本框）
          on-changeConditions2={this.changeConditions2.bind(this, item)}
          // 普通业务对象-输入条件（日期）
          on-changeDates={this.changeDates.bind(this, item)}
        />
      )
    },
    // eslint-disable-next-line
    renderDialogForm(h) {
      return (
        <DialogForm
          width='660px'
          closeOnClickModal={false}
          key={this.innerDialogType}
          class='addcondition-dialog'
          modalAppendToBody={true}
          visible={this.innerDialogType !== ''}
          title={this.innerDialogType === 'add' ? '新增条件' : '编辑条件'}
          on-close={this.handleCancel}>
          {this.renderCondition(h)}
          <c-form ref='form' slot='footer'>
            <c-form-item class='submit-btn'>
              <ButtonList operateBtnList={this.submitBtnList}></ButtonList>
            </c-form-item>
          </c-form>
        </DialogForm>
      )
    },
    // eslint-disable-next-line
    renderWrapTable(h) {
      return (
        <WrapTable
          ref='conditionTable'
          class='conditon-table'
          data={this.data}
          fields={this.columns}
          selectionCol={this.tableSelectionCol}
          indexCol={this.tableIndexCol}
          pagination={this.pagination}
          // autoLoad={ this.autoLoad }
          tooltip-effect='dark'
          border
          stripe
          // on-row-dblclick={ this.handleCurrentChange }
        >
          <c-row slot='toolPanel' class='toolPanel'>
            <c-col
              span={this.btnListWidthPercent}
              offset={this.btnListWidthOffset}>
              <ButtonList operateBtnList={this.toolPanelBtnList}></ButtonList>
            </c-col>
          </c-row>
          <c-table-column
            label='操作'
            align='center'
            slot='toolbar'
            fixed='right'
            width={this.tableOptWidth}
            {...{
              scopedSlots: {
                default: scope => {
                  return (
                    <TableButtonList
                      operateBtnList={this.tableRowBtnList}
                      props-model={scope.row}
                    />
                  )
                }
              }
            }}
          />
          }
        </WrapTable>
      )
    }
  },
  // eslint-disable-next-line
  render(h) {
    return (
      <div class='condition-config'>
        {this.renderWrapTable(h)}
        {this.renderDialogForm(h)}
      </div>
    )
  },
  beforeCreate() {
    const urlArr = ((this.$route.meta && this.$route.meta.children) || []).map(
      item => item.url
    )

    this.addBtns = [
      {
        label: '新增',
        methods: 'handleAdd',
        url: '',
        type: 'primary',
        icon: 'el-icon-circle-plus-outline',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.submitBtnList = [
      {
        label: '保存',
        methods: 'handleSubmit',
        url: '',
        icon: 'el-icon-circle-check-outline',
        type: 'primary',
        disabled: false
      },
      {
        label: '取消',
        methods: 'handleCancel',
        url: '',
        icon: 'el-icon-circle-close-outline',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.tableRowBtnList = [
      {
        label: '编辑',
        methods: 'handleEdit',
        url: '',
        icon: 'el-icon-edit-outline',
        type: 'primary',
        key: 'edit',
        align: 'top-start',
        disabled: false
      },
      {
        label: '删除',
        methods: 'handleDelete',
        url: '',
        icon: 'el-icon-delete',
        type: 'danger',
        key: 'delete',
        align: 'top-start',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)
  }
}
</script>

<style lang="scss">
.condition-config {
  box-sizing: border-box;
  .toolPanel {
    margin: 0 0 10px;
  }
  .el-icon-edit-outline {
    color: #409eff;
  }
  .el-icon-delete {
    color: #f56c6c;
  }
}
.el-tooltip__popper {
  max-width: 500px;
  word-wrap: break-word;
}
.addcondition-dialog {
  .common-box {
    margin-top: 10px;
    display: flex;
    align-items: center;
    .common-label {
      width: 120px;
    }
    .commonLine {
      flex: 1;
      .el-cascader {
        width: 100%;
      }
    }
  }
}
</style>
